package com.spring.lesson.tx;

import com.spring.lesson.jdbc.UserInfo;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class TestTxTemplate {

    private ApplicationContext context;
    private TransactionTemplate template;
    private JdbcTemplate jdbcTemplate;

    @Before
    public void init() {
        context = new ClassPathXmlApplicationContext("application-tx.xml");
        jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
        template = (TransactionTemplate) context.getBean("transactionTemplate");
    }

    @Test
    public void test1() throws Exception {
        template.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                // 增
                int row = jdbcTemplate.update("insert into t_user values(null,?,?)", "张三", "2018-10-21");
                // 改
                row = jdbcTemplate.update("update t_user set user_name=? where user_id = ?", "王五", 1);
                // 删
                row = jdbcTemplate.update("delete from t_user where user_id = ?", 11);

//                if (row == 0) {
//                    throw new RuntimeException();
//                }

                return row;
            }
        });
    }
    
}
